package servlet;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

/**
 * Servlet implementation class xxx
 */
@WebServlet("/xxx")
@MultipartConfig()
public class xxx extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public xxx() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request,response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("textml;charset=utf-8");
		response.setCharacterEncoding("utf-8");
		request.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		
		String name=request.getParameter("name");
		String picture=request.getParameter("picture");
		String time=request.getParameter("time");
		String place=request.getParameter("place");
		String telephone=request.getParameter("telephone");
		
		
		Part part=request.getPart("picture");//
	    String filename=getFilename(part);
	    writeTo(filename,part);
	    
	    out.print("success");
		
		//request.getRequestDispatcher("../Display.jsp").forward(request, response);
		
	}
	private String getFilename(Part part) {
        String header=part.getHeader("Content-Disposition");
        String filename=header.substring(header.indexOf("filename=\"")+10,header.lastIndexOf("\""));
		return filename;
    }

    private void writeTo(String filename,Part part) throws FileNotFoundException{
        InputStream in = null;
		try {
			in = part.getInputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}
        OutputStream out=new FileOutputStream("/"+filename);
        byte[] buffer=new byte[1024];
        int length=-1;
        try {
			while ((length=in.read(buffer))!=-1) {
				out.write(buffer,0,length);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			in.close();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
        try {
			out.close();
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
    }

	public void init() throws ServletException {
		// Put your code here
	}

}
